package com.gyh.system.gen.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gyh.system.common.persistence.BaseService;
import com.gyh.system.common.tools.StringUtils;
import com.gyh.system.gen.dao.ColumnsDao;
import com.gyh.system.gen.entity.Columns;
import com.gyh.system.gen.entity.Tables;
import com.gyh.system.gen.utils.ModelAttr;

/**
* @author 作者 gyh:
* @version 创建时间：2018年1月22日 下午11:11:21
* 
*/
@Service
public class ColumnsService extends BaseService<ColumnsDao, Columns>{
	
	@Autowired
	private ColumnsDao columnsDao;
	
	@Autowired
	private TablesService tablesService;
	
	/**
	 * 根据表名获取表中所有的字段属性
	 * @param table
	 * @return
	 */
	public List<Columns> searchColumns(String table){
		List<Columns> columns = columnsDao.searchColumns(table);
		for (Columns col : columns) {
			//将数据库中的字段名转换成java属性名
			col.setJavaName(StringUtils.underlineCaseToUpper(col.getJdbcName()));
			
			//根据jdbc字段类型设置java属性类型
			String javaType = StringUtils.substringBefore(col.getJdbcType(), "(");
			col.setJavaType(this.typeCase(javaType));
			String length = StringUtils.substringBetween(col.getJdbcType(), "(", ")");
			if (StringUtils.isNotBlank(length) && !StringUtils.equalsIgnoreCase("enum", javaType)) {
				col.setLength(Integer.parseInt(StringUtils.substringBefore(length, ",")));
			}
		}
		return columns;
	}

	
	
	public String typeCase(String type) {
		String result;
		switch (type) {
		case "text":
		case "varchar":
		case "enum":
		case "char":
			result = "String";
			break;
		case "datetime":
		case "timestamp":
		case "time":
		case "date":
			result = "Date";
			break;
		case "float":
			result = "Float";
			break;
		case "int":
		case "decimal":
		case "smallint":
		case "tinyint":
			result = "Integer";
			break;
		case "bigint":
		case "double":
			result = "Long";
			break;

		default:
			result = "";
			break;
		}
		return result;
	}


	public void addTableAndColumn(ModelAttr modelAttr) {
		Tables table = modelAttr.getTable();
		tablesService.save(table);
		for (Columns column : modelAttr.getColumns()) {
			column.settId(table.getId());
			this.save(column);
		}
	}
	

}
